package com.heng.atomics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

//副字段进行操作！局部的细粒度化的不加锁的原子更新
class BankAccout2{//资源类
    String bankName = "CCB";
    public volatile int money = 0;//必须要用volatile关键字，否则会报错！
    AtomicIntegerFieldUpdater<BankAccout2> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(BankAccout2.class,"money");
    //不加syn还要保证高性能原子性
    public void tansMoney(BankAccout2 bankAccout2) {
        fieldUpdater.getAndIncrement(bankAccout2);
    }
}

public class XXXAtomicIntegerFieldUpdaterDemo5 {
    public static void main(String[] args) throws InterruptedException {
        BankAccout2 bankAccout = new BankAccout2();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 1;i<=10 ;i++) {
            new Thread(()->{
                try{
                    for(int j = 1; j<= 1000;j++) {
                        bankAccout.tansMoney(bankAccout);
                    }
                }finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\tresult:"+bankAccout.money);

    }
}
